package com.atmilan.quartz.service.impl;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.SupplierUnmatchCategory;
import com.atmilan.quartz.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.atmilan.quartz.constant.Constants;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.constant.enums.SyncStatusEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttrValue;
import com.atmilan.quartz.model.entity.crmeb.SystemConfig;
import com.atmilan.quartz.model.entity.unibuy.UnibuyProduct;
import com.atmilan.quartz.model.entity.unibuy.UnibuyProductSku;
import com.atmilan.quartz.utils.RedisUtil;
import com.atmilan.quartz.utils.product.UnibuyProductUtil;
import com.atmilan.quartz.utils.source.SourceUnibuyProductUtil;
import com.atmilan.quartz.utils.unibuy.model.CommonQueryModel;
import com.atmilan.quartz.utils.unibuy.vo.goods.GoodsVO;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author daigb
 * @date:  2021-12-29 15:02
 */
@Slf4j
@Service
public class UnibuySyncServiceImpl implements IUnibuySyncService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ISystemConfigService systemConfigService;
    @Autowired
    IUnibuyProductService unibuyProductService;
    @Autowired
    IUnibuyProductSkuService unibuyProductSkuService;
    @Autowired
    IStoreProductService storeProductService;
    @Autowired
    IStoreProductAttrService storeProductAttrService;
    @Autowired
    IStoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    SourceUnibuyProductUtil sourceUnibuyProductUtil;
    @Autowired
    UnibuyProductUtil unibuyProductUtil;

    @Autowired
    ISupplierService supplierService;

    // 店铺编号
//    @Value("${unibuy.channelNos}")
//    private List<String> unibuyChannelNos;
    
    /**
     * 获取远程数据并保存到数据源
     */
    @Override
    public Boolean syncProduct() {
        // 数据清空
        unibuyProductService.deleteAll();
        unibuyProductSkuService.deleteAll();

        //2023.3.9修改unibuy接口获取方式
        List<Supplier> unibuySupplierList = supplierService.list(Wrappers.<Supplier>lambdaQuery()
                .isNotNull(Supplier::getUnibuyChannelno)
                .eq(Supplier :: getIsDeleted, false));
        for (Supplier supplier : unibuySupplierList) {
            int pageNo = 1;
            LocalDate endTime = LocalDate.now().plusDays(-1);
            LocalDate startTime = LocalDate.now().plusDays(-2);
            CommonQueryModel commonQueryModel = new CommonQueryModel();
            while (pageNo <= commonQueryModel.getMaxPage()) {
                try {
                    List<GoodsVO> goodsList = unibuyProductUtil.selectUnibuyPage(supplier, pageNo, commonQueryModel, startTime + " 00:00:00", endTime + " 00:00:00");
                    log.info("--------------- unibuy远程抓取{}数据, 第: {} 页, 总页数: {}  当前时间: {}, 总耗时: {} 分  ---------------",startTime, pageNo, commonQueryModel.getMaxPage(), startTime, (int) ((System.currentTimeMillis() - 100) / 1000 / 60));
                    if (CollectionUtils.isNotEmpty(goodsList)) {
                        // 商品保存
                        saveGoods(goodsList,supplier.getUnibuyChannelno());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                pageNo++;
            }
        }
        // 推送数据到生产库
        pushProduct();

        // 不知道之前怎么鬼写的
//        for(Supplier supplier:unibuySupplierList){
//
//            long millis = System.currentTimeMillis();
////        	LocalDate startTime = LocalDate.parse("2023-03-08");
//            LocalDate startTime = LocalDate.now().minusDays(30);
//            LocalDate endTime = startTime.plusDays(1);
//            while (LocalDate.now().plusDays(2).isAfter(endTime)) {
//                int pageNo = 1;
//                CommonQueryModel commonQueryModel = new CommonQueryModel();
//                while (pageNo <= commonQueryModel.getMaxPage()) {
//                    try {
//                        List<GoodsVO> goodsList = unibuyProductUtil.selectUnibuyPage(supplier, pageNo, commonQueryModel, startTime + " 00:00:00", endTime + " 00:00:00");
//                        log.info("--------------- unibuy远程抓取{}数据, 第: {} 页, 总页数: {}  当前时间: {}, 总耗时: {} 分  ---------------",startTime, pageNo, commonQueryModel.getMaxPage(), startTime, (int) ((System.currentTimeMillis() - millis) / 1000 / 60));
//                        if (CollectionUtils.isNotEmpty(goodsList)) {
//                            // 商品保存
//                            saveGoods(goodsList,supplier.getUnibuyChannelno());
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//
//                    pageNo++;
//                }
//
//                startTime = endTime;
//                endTime = endTime.plusDays(1);
//            }
//
//
//        }

//        for(String unibuyChannelNo : unibuyChannelNos) {
//        	long millis = System.currentTimeMillis();
////        	LocalDate startTime = LocalDate.parse("2022-03-01");
//        	LocalDate startTime = LocalDate.now().minusDays(30);
//        	LocalDate endTime = startTime.plusDays(1);
//        	while (LocalDate.now().plusDays(2).isAfter(endTime)) {
//        		int pageNo = 1;
//        		CommonQueryModel commonQueryModel = new CommonQueryModel();
//        		while (pageNo <= commonQueryModel.getMaxPage()) {
//        			try {
//        				List<GoodsVO> goodsList = unibuyProductUtil.selectUnibuyPage(unibuyChannelNo, pageNo, commonQueryModel, startTime + " 00:00:00", endTime + " 00:00:00");
//        				log.info("--------------- unibuy远程抓取{}数据, 第: {} 页, 总页数: {}  当前时间: {}, 总耗时: {} 分  ---------------",startTime, pageNo, commonQueryModel.getMaxPage(), startTime, (int) ((System.currentTimeMillis() - millis) / 1000 / 60));
//        				if (CollectionUtils.isNotEmpty(goodsList)) {
//        					// 商品保存
//        					saveGoods(goodsList);
//        				}
//        			} catch (Exception e) {
//        				e.printStackTrace();
//        			}
//
//        			pageNo++;
//        		}
//
//        		startTime = endTime;
//        		endTime = endTime.plusDays(1);
//        	}
//        }
    
        return true;
    }
    
    // 商品源数据保存
    private void saveGoods(List<GoodsVO> goodsList,String channelNo) {
        // 商品数据
        List<UnibuyProductSku> goodsEntity = new ArrayList<>();
        for(GoodsVO goods : goodsList) {
        	// 查询是否已存在
        	int skuCount = unibuyProductSkuService.count(Wrappers.<UnibuyProductSku>lambdaQuery()
        			.eq(UnibuyProductSku :: getSkuNo, goods.getSkuNo())
                     .eq(UnibuyProductSku :: getChannelNo, channelNo)
        			);
        	if(0 < skuCount) {
        		continue;
        	}
        	if(0 >= goods.getQuantity()) {
        		continue;
        	}
        	// 对象复制
            UnibuyProductSku productSkuEntity = new UnibuyProductSku();
            BeanUtils.copyProperties(goods, productSkuEntity);
            productSkuEntity.setGoodsDetailImage(JSON.toJSONString(goods.getGoodsDetailImage()));
            productSkuEntity.setPushTime(new Date());
            goodsEntity.add(productSkuEntity);
            // 查询主商品是否存在
            int productCount = unibuyProductService.count(Wrappers.<UnibuyProduct>lambdaQuery()
            		.eq(UnibuyProduct :: getGoodsNo, productSkuEntity.getGoodsNo())
            		.eq(UnibuyProduct :: getSourceArea, productSkuEntity.getSourceArea())
                    .eq(UnibuyProduct :: getChannelNo, channelNo)
            		);
            // TODO 待优化
            if(0 == productCount) {
                UnibuyProduct product = new UnibuyProduct();
                BeanUtils.copyProperties(productSkuEntity, product);
                product.setChannelNo(channelNo);
                unibuyProductService.save(product);
            }
        }
        
        unibuyProductSkuService.saveBatch(goodsEntity);
    }

    @Override
    public Boolean pushProduct() {
        try {
            // 当次更新少于1千条, 则不更新, 并且重新拉取
            int count = unibuyProductService.count();
            if (count == 0){
                return false;
            }
//			if(1000 > count) {
//			    systemConfigService.update(Wrappers.<SystemConfig>lambdaUpdate()
//			            .eq(SystemConfig :: getName, Constants.UNIBUY_SYNC_STATUS)
//			            .set(SystemConfig :: getFormId, SyncStatusEnum.PUSH)
//			            .set(SystemConfig :: getUpdateTime, new Date())
//			            );
//			    log.info("--------------- unibuy商品源数据, 少于规定条数, 不进行下发, 总条数为: {} ---------------", count);
//			    return false;
//			}

            List<Supplier> unibuySupplierList = supplierService.list(Wrappers.<Supplier>lambdaQuery()
                    .isNotNull(Supplier::getUnibuyChannelno)
                    .eq(Supplier :: getIsDeleted, false));

            for(Supplier supplier:unibuySupplierList){

                // 挪动下位置，供应商没有单子下面更新个锤子

                //2023.3.15获取对应商家店铺的数据
                int channelnoCount = unibuyProductService.count(Wrappers.<UnibuyProduct>lambdaQuery()
                        .eq(UnibuyProduct::getChannelNo, supplier.getUnibuyChannelno())
                );
                if (channelnoCount == 0) {
                    continue;
                }

                // 将所有unibuy商品更新状态置为未更新
                storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                        .eq(StoreProduct :: getIsEurope, supplier.getIsEurope())
                        .set(StoreProduct :: getUpdateFlag, false)
                );


                // 商品更新操作
                int pageNo = 1;
                int pageSize = 100;
                int maxPage = (channelnoCount + pageSize - 1) / pageSize;
                log.info("--------------- 开始分页查询unibuy商品源数据, 本次更新总条数为: {} ---------------", channelnoCount);

                long millis = System.currentTimeMillis();
                while (pageNo <= maxPage) {
                    try {
                        PageHelper.startPage(pageNo, pageSize);
                        List<UnibuyProduct> unibuyProducts = unibuyProductService.list(Wrappers.<UnibuyProduct>lambdaQuery()
                                        .eq(UnibuyProduct::getChannelNo, supplier.getUnibuyChannelno()));
                        PageInfo<UnibuyProduct> pageInfo = PageInfo.of(unibuyProducts);
                        List<UnibuyProduct> products = pageInfo.getList();
                        buildProduct(products,supplier);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("unibuy下发异常: ",e);
                    }

                    log.info("--------------- unibuy下发商品到数据库, 当前页数: {}, 总页数: {}, 耗时: {} 分 ---------------", pageNo, maxPage, (int)((System.currentTimeMillis() - millis) / 1000 / 60));
                    pageNo++;
                }

                // 下架所有未更新数据
                storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                        .eq(StoreProduct::getIsEurope, supplier.getIsEurope())
                        .eq(StoreProduct::getUpdateFlag, false)
                        .eq(StoreProduct :: getIsShow, true)
                        .eq(StoreProduct :: getIsDel, false)
                        .set(StoreProduct::getIsShow, false)
                        .set(StoreProduct::getStock, 0)
                        .set(StoreProduct::getLastPushTime, new Date())
                        .set(StoreProduct::getIsTusou, false)
                );
                // 下架所有sku库存
                storeProductService.downloadSku(supplier.getIsEurope());

            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return false;
    }
    
    /**
     * 下架商品并置空库存
     * @author daigb
     * @date:  2022-05-11 15:52
     */
    private void shutdowmProduct(String barCode,Supplier supplier) {
        // 图搜删除
        storeProductService.delSeachImageByBarcode(barCode);
        // 商品下架
    	storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
		        .eq(StoreProduct::getBarCode, barCode)
		        .eq(StoreProduct::getIsEurope, supplier.getIsEurope())
		        .eq(StoreProduct :: getIsShow, true)
		        .eq(StoreProduct :: getIsDel, false)
		        .set(StoreProduct::getIsShow, false)
		        .set(StoreProduct::getStock, 0)
		        .set(StoreProduct::getLastPushTime, new Date())
		        .set(StoreProduct::getIsTusou, false)
		        );
    	storeProductAttrValueService.update(Wrappers.<StoreProductAttrValue>lambdaUpdate()
    			.eq(StoreProductAttrValue :: getBarCode, barCode)
    			.set(StoreProductAttrValue :: getStock, 0)
    			);
    }

    /**
     * 商品构建处理
     * @Description:  
     * @author daigb 
     * @param @param products
     * @return void
     * @throws
     */
    private void buildProduct(List<UnibuyProduct> products,Supplier supplier) {
        try {
            for (UnibuyProduct product : products) {
                String barCode = supplier.getBarcode() + product.getGoodsNo().toString();
                barCode = barCode + "-" + StockAreaTempEnum.getByName(product.getSourceArea()).getTempId();
                
                if(0 == product.getIsDel()){
                	shutdowmProduct(barCode,supplier);
                    continue;
                }
                if(StringUtils.isEmpty(product.getGoodsMainImage())){
                	shutdowmProduct(barCode,supplier);
                	continue;
                }
                // sku数据
                List<UnibuyProductSku> skus = unibuyProductSkuService.list(Wrappers.<UnibuyProductSku>lambdaQuery()
                		.eq(UnibuyProductSku :: getGoodsNo, product.getGoodsNo())
                		.eq(UnibuyProductSku :: getSourceArea, product.getSourceArea())
//                		.gt(UnibuyProductSku :: getQuantity, 0)
                		);
                if(CollectionUtils.isEmpty(skus)) {
                	shutdowmProduct(barCode,supplier);
                    continue;
                }
                // 计算库存
                int stock = 0;
                for(UnibuyProductSku sku : skus) {
                	stock += sku.getQuantity();
                }
                if (0 >= stock) {
                	shutdowmProduct(barCode,supplier);
                    continue;
                }

                // 构建实体
                StoreProductCrmebRequest storeProductCrmebRequest = sourceUnibuyProductUtil.buildCrmebProduct(product, skus, stock,supplier);
                if(null == storeProductCrmebRequest) {
                	shutdowmProduct(barCode,supplier);
                    continue;
                }
                // 数据保存
                StoreProduct storeProduct = storeProductService.getByBarCode(storeProductCrmebRequest.getBarCode(), storeProductCrmebRequest.getSuppliersId(), storeProductCrmebRequest.getKeyword());
                storeProductService.saveOtProduct(storeProductCrmebRequest, storeProduct, stock);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}
